
Alkaline.Processing.ProcessingState = function(builder, tree) {
	this.builder = builder;
	var up = tree;
	while (up && !up.savedState)
		up = up.parent;
	if (up) {
		this.load(up);
		return;
	}
	this.globalContext = tree.globalContext = new Alkaline.Processing.LexicalContext(null, tree, this.builder);
	this.functionContexts = [this.globalContext];
	this.blockContexts = [this.globalContext];
	this.currentContext = this.globalContext;
	this.contextStack = [this.globalContext];
	this.condition = Alkaline.Processing.Condition.ALWAYS;
	this.conditionStack = [this.condition];
}

Alkaline.Processing.ProcessingState.prototype.pushContext = function(context) {
	this.currentContext = context;
	this.contextStack.push(context);
	this.blockContexts.push(context);
	if (context.isFunctionContext)
		this.functionContexts.push(context);
}

Alkaline.Processing.ProcessingState.prototype.popContext = function() {
	var context = this.contextStack.pop();
	if (this.blockContexts.last() == context)
		this.blockContexts.pop();
	if (this.functionContexts.last() == context)
		this.functionContexts.pop();
	this.currentContext = this.contextStack.last();
	return context;
}

Alkaline.Processing.ProcessingState.prototype.pushCondition = function(newCondition) {
	this.conditionStack.push(this.condition);
	this.condition = newCondition;
}

Alkaline.Processing.ProcessingState.prototype.popCondition = function() {
	this.condition = this.conditionStack.pop();
}

Alkaline.Processing.ProcessingState.prototype.propertiesSaved = ['globalContext', 'functionContexts', 'blockContexts', 'currentContext', 'contextStack', 'condition', 'conditionStack'];
Alkaline.Processing.ProcessingState.prototype.save = function(tree) {
	var obj = {};
	for (var i = 0; i < this.propertiesSaved.length; i++) {
		var prop = this.propertiesSaved[i];
		var save = this[prop];
		if (save instanceof Array)
			save = save.concat([]);
		obj[prop] = save;
	}
	tree.savedState = obj;
}

Alkaline.Processing.ProcessingState.prototype.load = function(tree) {
	var savedState = tree.savedState;
	for (var i = 0; i < this.propertiesSaved.length; i++) {
		var prop = this.propertiesSaved[i];
		var item = savedState[prop];
		if (item instanceof Array)
			item = item.concat([]);
		this[prop] = item;
	}
}

Alkaline.Processing.ProcessingState.prototype.matches = function(tree) {
	var savedState = tree.savedState;
	return this.currentContext === savedState.currentContext;
}
